package com.autumn.juc.lock;

import com.autumn.juc.factory.UnsafeFactory;
import sun.misc.Unsafe;

public class CASLock {
    //加锁标记
    private volatile int state;
    private static Unsafe UNSAFE;
    private static long OFFSET;

    static {
        try {
            UNSAFE = UnsafeFactory.getUnsafe();
            OFFSET = UnsafeFactory.getFieldOffset(
                    UNSAFE, CASLock.class, "state"
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean cas() {
        return UNSAFE.compareAndSwapInt(this, OFFSET, 0, 1);
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }
}
